import { Rect, view } from "cc";
import { ecsclass, ECSSystem } from "../../../app-core/ecs/ECSWorld";
import { MovableComponent } from "../components/MovableComponent";
import { NpcRenderComponent } from "../components/NpcRenderComponent";

@ecsclass('MovableSystem')
export class MovableSystem extends ECSSystem {

    readonly rect: Rect;

    constructor() {
        super();

        const winSize = view.getVisibleSize();

        this.rect = new Rect(-winSize.width / 2 - 32, -winSize.height / 2 - 32, winSize.width + 64, winSize.height + 64);
    }

    update(dt: number) {
        const movables = this.ecs.components.all(MovableComponent);

        movables.forEach((movable) => {
            switch (movable.direction) {
                case 'up': {
                    movable.position.y += movable.speed * dt;
                    break;
                }

                case 'down': {
                    movable.position.y -= movable.speed * dt;
                    break;
                }

                case 'left': {
                    movable.position.x -= movable.speed * dt;
                    break;
                }

                case 'right': {
                    movable.position.x += movable.speed * dt;
                    break;
                }
            }

            if (movable.position.x < this.rect.xMin) {
                movable.position.x = this.rect.xMax;
            } else if (movable.position.x > this.rect.xMax) {
                movable.position.x = this.rect.xMin;
            }

            if (movable.position.y > this.rect.yMax) {
                movable.position.y = this.rect.yMin;
            } else if (movable.position.y < this.rect.yMin) {
                movable.position.y = this.rect.yMax;
            }

            const entity = this.ecs.entities.get(movable.entityId);
            if (entity.hasComponent(NpcRenderComponent)) {
                const render = entity.getComponent(NpcRenderComponent);
                render.node.setPosition(movable.position);
            }
        })
    }
}